package com.chii.image.service.impl;

import com.chii.image.service.ImageService;
import com.chii.image.utils.FtpClientUtil;
import com.chii.image.utils.QiNiuUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.UUID;

@Service
public class ImageServiceImpl implements ImageService {
    private Logger logger = LogManager.getLogger(ImageServiceImpl.class);
    @Autowired
    private FtpClientUtil ftpClientUtil;
    @Autowired
    private QiNiuUtils qiNiuUtils;
    @Value("${localhost.FTPHost}")
    private String FTPHost;
    @Value("${upload.path}")
    private String PATH;

    @Override
    public String saveImageLocal(MultipartFile file, String fileName) throws IOException {
        File f = new File(PATH);
        if (!f.exists() && f.mkdirs()) {
            logger.info("创建文件夹成功:" + f.getAbsolutePath());
        }
        //根据获取到的原始文件名创建目标文件
        String outPutName = PATH + fileName;
        File image = new File(outPutName);
        //将收到的文件传输到目标文件中
        file.transferTo(image);
        return outPutName;
    }

    @Override
    public String saveBase64ImageLocal(String file, String fileName) throws IOException {

        byte[] bs = Base64Utils.decodeFromString(file);
        String outPutName = PATH + fileName;
        FileOutputStream os = new FileOutputStream(outPutName);
        os.write(bs);
        os.close();
        return outPutName;
    }

    @Override
    public String saveImageFTP(MultipartFile file, String fileName) throws IOException {
        ftpClientUtil.creat();
        if (ftpClientUtil.upload(file, fileName)) {
            return FTPHost + fileName;
        }
        return null;
    }

    @Override
    public String saveBase64ImageFTP(String file, String fileName) throws IOException {
        byte[] bs = Base64Utils.decodeFromString(file);
        InputStream sbs = new ByteArrayInputStream(bs);
        ftpClientUtil.creat();
        if (ftpClientUtil.upload(sbs, fileName)) {
            return FTPHost + fileName;
        }
        return null;
    }

    @Override
    public String saveImageQiNiu(MultipartFile file, String fileName) throws IOException {
        //上传wav到七牛云
        String url = qiNiuUtils.upload(fileName,file.getInputStream());
        return url;
    }

    @Override
    public String saveBase64ImageQiNiu(String file, String fileName) throws IOException {
        byte[] bs = Base64Utils.decodeFromString(file);
        InputStream sbs = new ByteArrayInputStream(bs);
        String url = qiNiuUtils.upload(fileName,sbs);
        return url;
    }

}
